package com.serviceprovider.business.module.admin.acl.services.dao.impl;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.acl.model.AclClass;
import com.serviceprovider.business.module.admin.acl.services.dao.interfaces.IAclClassService;
import com.serviceprovider.business.module.common.Page;
import com.serviceprovider.business.module.common.PaginationHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;

//~--- JDK imports ------------------------------------------------------------

import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Owat
 *
 */
@Service("aclClassService")
public class AclClassServiceImpl extends JdbcDaoSupport implements IAclClassService {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    public AclClassServiceImpl(@Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate) {
        setJdbcTemplate(jdbcTemplate);
    }

    /*
     * (non-Javadoc)
     *
     * @see springjdbc.example.service.RoleService#findAll()
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<AclClass> findAll() {
        String         sql  = "select id,class,name  from acl_class";    // $NON-NLS-1$
        List<Map>      list = getJdbcTemplate().queryForList(sql);
        List<AclClass> ret  = new ArrayList<AclClass>();
        Map            row  = null;
        AclClass       aux  = null;

        for (Object obj : list) {
            row = (Map) obj;
            aux = new AclClass();
            aux.setId(Integer.valueOf(String.valueOf(row.get("id"))));    // $NON-NLS-1$
            aux.setId(Integer.valueOf(String.valueOf(row.get("id"))));    // $NON-NLS-1$
            aux.setClassName(String.valueOf(row.get("class")));
            aux.setName(String.valueOf(row.get("name")));                 // $NON-NLS-1$
            ret.add(aux);
        }

        return ret;
    }

    private boolean getBoolean(Object val) {
        return (val != null) && ("true".equals(val.toString()) || val.toString().equals("1"));
    }

    /*
     * (non-Javadoc)
     *
     * @see springjdbc.example.service.RoleService#getRole(int)
     */
    public AclClass getAclClassById(int id) {
        RowMapper mapper = new RowMapper() {
            public AclClass mapRow(ResultSet rs, int rowNum) throws SQLException {
                AclClass role = new AclClass();

                AclClassServiceImpl.mapRow(role, rs);

                return role;
            }
        };
        final String sql = "select id,class,name  from acl_class where id = ?";    // $NON-NLS-1$

        try {
            return (AclClass) getJdbcTemplate().queryForObject(sql, new Object[] { id }, mapper);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private static void mapRow(AclClass obj, ResultSet rs) throws SQLException {
        obj.setId(rs.getInt("id"));                 // $NON-NLS-1$
        obj.setName(rs.getString("name"));          // $NON-NLS-1$
        obj.setClassName(rs.getString("class"));    // $NON-NLS-1$
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * springjdbc.example.service.RoleService#insertRole(springjdbc.example.
     * domain.Role)
     */
    public void insertAclClass(AclClass obj) {
        if (checkIfNameOrClassNameAlreadyPresent(obj)) {
            return;    // exception should be thrown from here
        }

        final String sql = "insert into acl_class (name,class) values(?,?)";    // $NON-NLS-1$

        getJdbcTemplate().update(sql, new Object[] { obj.getName(), obj.getClassName() });
    }

    private boolean checkIfNameOrClassNameAlreadyPresent(AclClass obj) {
        RowMapper mapper = new RowMapper() {
            public AclClass mapRow(ResultSet rs, int rowNum) throws SQLException {
                AclClass role = new AclClass();

                AclClassServiceImpl.mapRow(role, rs);

                return role;
            }
        };
        final String sql = "select  id,class,name from acl_class where name = ? or class = ?";    // $NON-NLS-1$

        try {
            AclClass aclClass = (AclClass) getJdbcTemplate().queryForObject(sql, new Object[] { obj.getName(),
                    obj.getClassName() }, mapper);

            if (aclClass != null) {
                return true;
            }

            return false;
        } catch (EmptyResultDataAccessException e) {
            return false;
        }
    }

    public void updateAclClass(AclClass obj) {
        final String sql = "update acl_class set name = ? , class = ? where id = ?";    // $NON-NLS-1$

        getJdbcTemplate().update(sql, new Object[] { obj.getName(), obj.getClassName(), obj.getId() });
    }

    public void deleteAclClassesById(int[] idList) {
        final String sql = "delete from acl_class where id = ?";    // $NON-NLS-1$

        for (int i = 0; i < idList.length; i++) {
            getJdbcTemplate().update(sql, new Object[] { Integer.valueOf(idList[i]) });
        }
    }

    public Page<AclClass> findAll(int pageNo, int recordSize, String sortColumn, String sortOrder) {
        PaginationHelper<AclClass>       pageHelper = new PaginationHelper<AclClass>();
        ParameterizedRowMapper<AclClass> mapper     = new AclClassRowMapper();
        String                           sql        = "select id,class,name  from acl_class order by " + sortColumn + " " + sortOrder;    // $NON-NLS-1$
        String                           countSql   = "SELECT COUNT(*) FROM acl_class";

        return pageHelper.fetchPage(getJdbcTemplate(), countSql, sql, new Object[] {}, pageNo, recordSize, sortColumn,
                                    sortOrder, mapper);
    }

    private static class AclClassRowMapper implements ParameterizedRowMapper<AclClass> {
        @Override
        public AclClass mapRow(ResultSet rs, int index) throws SQLException {
            AclClass aclClass = new AclClass();

            aclClass.setId(rs.getInt("id"));           // $NON-NLS-1$
            aclClass.setClassName(rs.getString("class"));
            aclClass.setName(rs.getString("name"));    // $NON-NLS-1$

            return aclClass;
        }
    }
}



